<script setup lang="ts">
import { ref, inject, onMounted } from 'vue'
import regexUtil from '../../util/RegexUtil'
import captchaData from '../../data/CaptchaData'
import { DateTime } from 'luxon'
import { db } from '../../db/db'
import $ from 'jquery'
import 'bootstrap/dist/js/bootstrap'
import { useRouter } from 'vue-router'

const router = useRouter()

const schoolData: any = ref([])

onMounted(async () => {
  const dbSchoolData = await db.school.where('schoolIsDel').equals(0).toArray()
  schoolData.value = dbSchoolData
})

const form = ref({
  schoolId: '',
  studentNumber: '',
  username: '',
  realName: '',
  phoneNumber: '',
  code: '',
  password: '',
  okPassword: ''
})
const formErr = ref({
  schoolId: false,
  studentNumber: false,
  username: false,
  realName: false,
  phoneNumber: false,
  code: false,
  password: false,
  okPassword: false
})
const formMsg = ref({
  schoolId: '',
  studentNumber: '',
  username: '',
  realName: '',
  phoneNumber: '',
  code: '',
  password: '',
  okPassword: ''
})

const axios: any = inject('axios')

const verificationCode = ref('验证码')
const verificationCodeBtnState = ref(false)

let randomVc = 0

const count = 120 //间隔函数，1秒执行
let curCount = 0 //当前剩余秒数
let interValObj: any
function obtainCode() {
  if (!checkPhoneNumber()) {
    return
  } else {
    randomVc = Math.floor(Math.random() * (9999 - 1000 + 1)) + 1000

    axios
      .post('/overt/system/sms/verification-code', {
        token: 'bezG5CJQ8DDm',
        phoneNumber: form.value.phoneNumber,
        code: randomVc
      })
      .then(function (response: any) {
        if (response.data.state) {
          curCount = count
          //设置button效果，开始计时
          verificationCodeBtnState.value = true
          verificationCode.value = curCount + '秒'
          interValObj = window.setInterval(setRemainTime, 1000)
        }
      })
      .catch(function (error: any) {
        console.log(error)
      })
  }


}

function setRemainTime() {
  if (curCount === 0) {
    window.clearInterval(interValObj) //停止计时器
    verificationCodeBtnState.value = false
    verificationCode.value = '验证码'
  } else {
    curCount--
    verificationCode.value = curCount + '秒'
  }
}

function checkSchoolId() {
  formErr.value.schoolId = false
  formMsg.value.schoolId = ''
  if (form.value.schoolId === '') {
    formErr.value.schoolId = true
    formMsg.value.schoolId = '请选择学校'
    return false
  }
  return true
}

async function checkStudentNumber() {
  formErr.value.studentNumber = false
  formMsg.value.studentNumber = ''
  if (form.value.studentNumber === '') {
    formErr.value.studentNumber = true
    formMsg.value.studentNumber = '学号不能为空'
    return false
  } else {
    if (!regexUtil.studentNumber.test(form.value.studentNumber)) {
      formErr.value.studentNumber = true
      formMsg.value.studentNumber = '学号13位数字'
      return false
    }
    let sd = await db.student.where({ 'schoolId': form.value.schoolId, 'studentNumber': form.value.studentNumber }).toArray()
    if (sd.length > 0) {
      formErr.value.studentNumber = true
      formMsg.value.studentNumber = '学号已存在'
      return false
    }
  }
  return true
}

async function checkUsername() {
  formErr.value.username = false
  formMsg.value.username = ''
  if (form.value.username === '') {
    formErr.value.username = true
    formMsg.value.username = '账号不能为空'
    return false
  } else {
    if (!regexUtil.username.test(form.value.username)) {
      formErr.value.username = true
      formMsg.value.username = '账号为1~20位字母,数字'
      return false
    }

    const tempUers = await db.users.where('username').equals(form.value.username).toArray()

    if (tempUers.length > 0) {
      formErr.value.username = true
      formMsg.value.username = '账号已存在'
      return false
    }
  }
  return true
}

function checkRealName() {
  formErr.value.realName = false
  formMsg.value.realName = ''
  if (form.value.realName === '') {
    formErr.value.realName = true
    formMsg.value.realName = '姓名不能为空'
    return false
  }
  return true
}

async function checkPhoneNumber() {
  formErr.value.phoneNumber = false
  formMsg.value.phoneNumber = ''
  if (form.value.phoneNumber === '') {
    formErr.value.phoneNumber = true
    formMsg.value.phoneNumber = '手机号不能为空'
    return false
  } else {
    if (!regexUtil.mobile.test(form.value.phoneNumber)) {
      formErr.value.phoneNumber = true
      formMsg.value.phoneNumber = '手机号11位数字'
      return false
    }

    let tempPn = await db.student.where('phoneNumber').equals(form.value.phoneNumber).toArray()
    if (tempPn.length > 0) {
      formErr.value.phoneNumber = true
      formMsg.value.phoneNumber = '手机号已被注册'
      return false
    }
  }
  return true
}

function checkCode() {
  formErr.value.code = false
  formMsg.value.code = ''
  if (form.value.code === '') {
    formErr.value.code = true
    formMsg.value.code = '验证码不能为空'
    return false
  } else {
    // if (captchaData.indexOf(form.value.code) < 0) {
    if (randomVc != Number(form.value.code)) {
      formErr.value.code = true
      formMsg.value.code = '验证码错误'
      return false
    }
  }
  return true
}

function checkPassword() {
  formErr.value.password = false
  formMsg.value.password = ''
  if (form.value.password === '') {
    formErr.value.password = true
    formMsg.value.password = '密码不能为空'
    return false
  } else {
    if (!regexUtil.password.test(form.value.password)) {
      formErr.value.password = true
      formMsg.value.password = '密码为6~20位字母,数字及特殊字符'
      return false
    }
  }
  return true
}

function checkOkPassword() {
  formErr.value.okPassword = false
  formMsg.value.okPassword = ''
  if (form.value.okPassword === '') {
    formErr.value.okPassword = true
    formMsg.value.okPassword = '确认密码不能为空'
    return false
  } else {
    if (!regexUtil.password.test(form.value.okPassword)) {
      formErr.value.okPassword = true
      formMsg.value.okPassword = '密码为6~20位字母,数字及特殊字符'
      return false
    }

    if (form.value.password != form.value.okPassword) {
      formErr.value.okPassword = true
      formMsg.value.okPassword = '密码不相同'
      return false
    }
  }
  return true
}

// Submit function
const submitForm = () => {
  if (!checkSchoolId()) {
    return false
  }

  if (!checkStudentNumber()) {
    return false
  }

  if (!checkUsername()) {
    return false
  }

  if (!checkRealName()) {
    return false
  }

  if (!checkPhoneNumber()) {
    return false
  }

  if (!checkCode()) {
    return false
  }

  if (!checkPassword()) {
    return false
  }

  if (!checkOkPassword()) {
    return false
  }

  db.users.add({
    username: form.value.username,
    password: form.value.password,
    enabled: 1,
    realName: form.value.realName,
    avatar: '/img/avatar2.jpg',
    joinDate: DateTime.now().toFormat('yyyy-LL-dd'),
    usersTypeId: 4
  })

  db.student.add({
    studentNumber: form.value.studentNumber,
    phoneNumber: form.value.phoneNumber,
    qq: '',
    weixin: '',
    schoolId: Number(form.value.schoolId),
    username: form.value.username
  })

  $('#successModal').modal('show')
}

const toLogin = () => {
  $('#successModal').modal('hide')
  router.push({ path: '/web/login' })
}
</script>

<template>
  <form @submit.prevent="submitForm">
    <div class="form-group">
      <select class="form-control" :class="formErr.schoolId ? 'is-invalid' : ''" v-model="form.schoolId"
        @change="checkSchoolId">
        <option value="">请选择学校</option>
        <option v-for="school in schoolData" :value="school.schoolId">
          {{ school.schoolName }}
        </option>
      </select>
      <div class="invalid-feedback">
        {{ formMsg.schoolId }}
      </div>
    </div>
    <div class="form-group">
      <input type="text" class="form-control" :class="formErr.studentNumber ? 'is-invalid' : ''"
        v-model.trim="form.studentNumber" placeholder="学号" @blur="checkStudentNumber" />
      <div class="invalid-feedback">
        {{ formMsg.studentNumber }}
      </div>
    </div>
    <div class="form-group">
      <input type="text" class="form-control" :class="formErr.username ? 'is-invalid' : ''" v-model.trim="form.username"
        placeholder="账号" @blur="checkUsername" />
      <div class="invalid-feedback">
        {{ formMsg.username }}
      </div>
    </div>
    <div class="form-group">
      <input type="text" class="form-control" :class="formErr.realName ? 'is-invalid' : ''" v-model.trim="form.realName"
        placeholder="姓名" @blur="checkRealName" />
      <div class="invalid-feedback">
        {{ formMsg.realName }}
      </div>
    </div>
    <div class="form-group">
      <div class="input-group is-invalid">
        <input type="text" class="form-control" :class="formErr.phoneNumber ? 'is-invalid' : ''"
          v-model.trim="form.phoneNumber" placeholder="手机号" @blur="checkPhoneNumber" />
        <div class="input-group-append">
          <button class="btn btn-outline-secondary" type="button" @click="obtainCode"
            :disabled="verificationCodeBtnState">
            {{ verificationCode }}
          </button>
        </div>
      </div>
      <div class="invalid-feedback" style="display: block">
        {{ formMsg.phoneNumber }}
      </div>
    </div>
    <div class="form-group">
      <input type="text" class="form-control" :class="formErr.code ? 'is-invalid' : ''" v-model.trim="form.code"
        placeholder="验证码" @blur="checkCode" />
      <div class="invalid-feedback">
        {{ formMsg.code }}
      </div>
    </div>
    <div class="form-group">
      <input type="password" class="form-control" :class="formErr.password ? 'is-invalid' : ''"
        v-model.trim="form.password" placeholder="密码" @blur="checkPassword" />
      <div class="invalid-feedback">
        {{ formMsg.password }}
      </div>
    </div>
    <div class="form-group">
      <input type="password" class="form-control" :class="formErr.okPassword ? 'is-invalid' : ''"
        v-model.trim="form.okPassword" placeholder="确认密码" @blur="checkOkPassword" />
      <div class="invalid-feedback">
        {{ formMsg.okPassword }}
      </div>
    </div>
    <button type="submit" class="btn btn-success btn-round btn-block shadow-sm">注 册</button>
  </form>

  <!-- Modal -->
  <div class="modal fade" id="successModal" tabindex="-1" aria-labelledby="successModalLabel" aria-hidden="true"
    style="z-index: 9000;">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title text-success" id="successModalLabel">注册成功</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          您好，您已注册成功！
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
          <button type="button" class="btn btn-primary" @click="toLogin">去登录</button>
        </div>
      </div>
    </div>
  </div>
</template>
